package com.xjiye_test.payServer.servletGroup.weixin;

import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.db.Page;
import com.xiaoleilu.hutool.db.PageResult;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xjiye_test.payServer.dao.OrderDao;
import com.xjiye_test.payServer.pojo.PayRecord;
import com.xjiye_test.payServer.serverletUtil.IdWorker;
import com.xjiye_test.payServer.serverletUtil.ReadBytes;
import com.xjiye_test.payServer.serverletUtil.Signature;
import com.xjiye_test.payServer.serverletUtil.XMLParser;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/5/19.
 */
public class WeixinMicropay extends HttpServlet {
    protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String reStr=null;
        try {
            req.setCharacterEncoding("UTF-8");
            int size = req.getContentLength();
            InputStream is = req.getInputStream();
            Map mapRequest = XMLParser.getMapFromXML(new String(ReadBytes.readBytes(is, size)));
            OrderDao orderdao=new OrderDao();
            List<String> keys= new ArrayList<>();
            List<String> values= new ArrayList<>();
            keys.add("suppOrderNo=");
            values.add(mapRequest.get("out_trade_no").toString());
            keys.add("suppId=");
            values.add(mapRequest.get("mch_id").toString());
            PageResult<Entity> order=orderdao.getDataByCondition(new Page(0,10),keys,values);
            if(order.isEmpty()){
                //构造订单对象
                String transid=IdWorker.getIdWorker().nextId()+"";
                String openid= RandomUtil.randomString(29);
                PayRecord pay=new PayRecord();
                pay.setTime(new Date());
                pay.setAppid(mapRequest.get("appid").toString());
                pay.setSuppId(mapRequest.get("mch_id").toString());
                pay.setWechatOrderNo(transid);
                pay.setSuppOrderNo(mapRequest.get("out_trade_no").toString());
                pay.setOpenid(openid);
                pay.setPaytype("MICROPAY");
                pay.setPaystatus("SUCCESS");
                pay.setAmount(Integer.parseInt(mapRequest.get("total_fee").toString()));
                pay.setWechatRefundNo("");
                pay.setSuppRefundNo("");
                pay.setRefundAmount(0);
                pay.setFee(3);
                pay.setFeeAmount((new Double(NumberUtil.round(NumberUtil.mul(Integer.parseInt(mapRequest.get("total_fee").toString())/100.00,0.003),0))).intValue());
                orderdao.addOrderInfo(pay);
                reStr = Signature.getSignFromResponseString("<xml>\n" +
                        "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                        "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                        "   <appid><![CDATA["+mapRequest.get("appid")+"]]></appid>\n" +
                        "   <mch_id><![CDATA["+mapRequest.get("mch_id")+"]]></mch_id>\n" +
                        "   <device_info><![CDATA[1000]]></device_info>\n" +
                        "   <nonce_str><![CDATA[GOp3TRyMXzbMlkun]]></nonce_str>\n" +
                        "   <sign><![CDATA[D6C76CB785F07992CDE05494BB7DF7FD]]></sign>\n" +
                        "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                        "   <openid><![CDATA["+ openid+"]]></openid>\n" +
                        "   <is_subscribe><![CDATA[Y]]></is_subscribe>\n" +
                        "   <trade_type><![CDATA[MICROPAY]]></trade_type>\n" +
                        "   <bank_type><![CDATA[CCB_DEBIT]]></bank_type>\n" +
                        "   <total_fee>"+mapRequest.get("total_fee")+"</total_fee>\n" +
                        "   <coupon_fee>0</coupon_fee>\n" +
                        "   <fee_type><![CDATA[CNY]]></fee_type>\n" +
                        "   <transaction_id><![CDATA["+transid+"]]></transaction_id>\n" +
                        "   <out_trade_no><![CDATA["+mapRequest.get("out_trade_no")+"]]></out_trade_no>\n" +
                        "   <attach><![CDATA[ok]]></attach>\n" +
                        "   <time_end><![CDATA[20141111170043]]></time_end>\n" +
                        "</xml>", "123456");
            }else {
                reStr="<xml><return_code><![CDATA[FAIL]]></return_code>\n" +
                        "<return_msg><![CDATA[订单号重复]]></return_msg>\n" +
                        "</xml>";
            }

        } catch (IOException e) {
            e.printStackTrace();
            reStr="<xml><return_code><![CDATA[FAIL]]></return_code>\n" +
                    "<return_msg><![CDATA[XML解析错误]]></return_msg>\n" +
                    "</xml>";
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            reStr="<xml><return_code><![CDATA[FAIL]]></return_code>\n" +
                    "<return_msg><![CDATA[系统错误]]></return_msg>\n" +
                    "</xml>";
        } catch (SAXException e) {
            e.printStackTrace();
            reStr="<xml><return_code><![CDATA[FAIL]]></return_code>\n" +
                    "<return_msg><![CDATA[编码错误]]></return_msg>\n" +
                    "</xml>";
        }catch (SQLException e) {
            e.printStackTrace();
            reStr="<xml><return_code><![CDATA[FAIL]]></return_code>\n" +
                    "<return_msg><![CDATA[系统错误]]></return_msg>\n" +
                    "</xml>";
        } finally {
            out.println(reStr);
            out.flush();
        }
    }

    protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
